package com.sz.dao.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.junit.Test;

public class TypeChange {
	@Test
	public void t1() {
		int i = 233;
		String str = (String) typeClass(String.class, i);
		System.out.println(str);
	}
	
	public static Object typeString(String newTypeString, Object object) {
		try {
			Class c = Class.forName(newTypeString);
			return typeClass(c, object);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 类型转换方法--使用反射机制
	 * @param newObjectClass 转换成新的类型的Class类 
	 * @param object 要被转换的对象
	 * @return 新的的类型
	 */
	public static Object typeClass(Class newObjectClass, Object object) {
		String[] str = new String[] { "Integer", "String", "Date", "int" };
		String oldString = object.getClass().getTypeName();
		System.out.println(object.getClass().getTypeName());
		String newString = newObjectClass.getName();
		String ol = null;
		String ne = null;

		Object uu = null;

		for (int i = 0; i < str.length; i++) {
			if (oldString.contains(str[i]) && ol == null) {
				ol = str[i];
			}
			if (newString.contains(str[i]) && ne == null) {
				ne = str[i];
			}
			if (ne != null && ol != null) {
				break;
			}
		}
		if (ol.equals(ne)) {
			return uu = object;
		} else if (ol.equals("Integer") && ne.equals("String")) {
			return uu = intToString(object);
		} else if (ol.equals("String") && ne.equals("Integer")) {
			return uu = Integer.valueOf((String) object);
		} else if (ol.equals("String") && ne.equals("Date")) {
			try {
				return uu = stringToDate(object);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else if (ol.equals("Date") && ne.equals("String")) {
			return uu = dateToString(object);
		}
		return uu;
	}

	public static String intToString(Object object) {
		return String.valueOf((int) object);
	}

	public static int stringToInt(String object) {
		return Integer.valueOf((String) object);
	}

	public static Date stringToDate(Object object) throws ParseException {
		SimpleDateFormat sim = new SimpleDateFormat();
		return sim.parse((String) object);
	}

	public static String dateToString(Object object) {
		SimpleDateFormat sim = new SimpleDateFormat();
		return sim.format(object);
	}
}
